package cn.six1943.deepchat.module.ai.service.chatsession;

import cn.hutool.core.collection.CollUtil;
import cn.six1943.deepchat.module.ai.dal.mysql.chatsession.ChatMsgMapper;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import java.util.*;
import cn.six1943.deepchat.module.ai.controller.admin.chatsession.vo.*;
import cn.six1943.deepchat.module.ai.dal.dataobject.chatsession.ChatMsgDO;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;


import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.six1943.deepchat.module.ai.enums.ErrorCodeConstants.*;

/**
 * 会话消息 Service 实现类
 *
 * @author noday
 */
@Service
@Validated
public class ChatMsgServiceImpl implements ChatMsgService {

    @Resource
    private ChatMsgMapper chatMsgMapper;

    @Override
    public Long createChatMsg(ChatMsgSaveReqVO createReqVO) {
        // 插入
        ChatMsgDO chatMsg = BeanUtils.toBean(createReqVO, ChatMsgDO.class);
        chatMsgMapper.insert(chatMsg);
        // 返回
        return chatMsg.getId();
    }

    @Override
    public void updateChatMsg(ChatMsgSaveReqVO updateReqVO) {
        // 校验存在
        validateChatMsgExists(updateReqVO.getId());
        // 更新
        ChatMsgDO updateObj = BeanUtils.toBean(updateReqVO, ChatMsgDO.class);
        chatMsgMapper.updateById(updateObj);
    }

    @Override
    public void deleteChatMsg(Long id) {
        // 校验存在
        validateChatMsgExists(id);
        // 删除
        chatMsgMapper.deleteById(id);
    }

    @Override
        public void deleteChatMsgListByIds(List<Long> ids) {
        // 校验存在
        validateChatMsgExists(ids);
        // 删除
        chatMsgMapper.deleteByIds(ids);
        }

    private void validateChatMsgExists(List<Long> ids) {
        List<ChatMsgDO> list = chatMsgMapper.selectByIds(ids);
        if (CollUtil.isEmpty(list) || list.size() != ids.size()) {
            throw exception(CHAT_MSG_NOT_EXISTS);
        }
    }

    private void validateChatMsgExists(Long id) {
        if (chatMsgMapper.selectById(id) == null) {
            throw exception(CHAT_MSG_NOT_EXISTS);
        }
    }

    @Override
    public ChatMsgDO getChatMsg(Long id) {
        return chatMsgMapper.selectById(id);
    }

}